package com.xmy.servlet;

import com.xmy.entity.User;
import com.xmy.service.UserService;
import com.xmy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户操作
 */
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        UserService us = new UserServiceImpl();
        String method = request.getParameter("method");
        if (method.equals("login")){
            String uname = request.getParameter("username");
            String pwd = request.getParameter("password");
            String yzm = request.getParameter("yzm");
            User user = us.selByNameAndPwd(uname, pwd);
            String sission_yzm = (String) request.getSession().getAttribute("checkcode_session");//获取保存到sission中的验证码
            if (user!=null && sission_yzm.equals(yzm)){//验证码和用户名密码验证
                request.getSession().setAttribute("user",user);
                request.getSession().setMaxInactiveInterval(30*60);
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }else{
                if (user==null){
                    request.setAttribute("msg","用户名或密码错误！");
                }else if(yzm!=sission_yzm){
                    request.setAttribute("msg","验证码错误！");
                }
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        }else if(method.equals("logout")){//注销
            request.getSession().invalidate();//清除session中的用户数据
            response.sendRedirect("index.jsp");//重定向到主页
        }
    }
}
